<template>
  <div class="admin-menus">
    <div class="page-header">
      <h2>菜单管理</h2>
      <div class="header-actions">
        <el-button 
          type="primary" 
          @click="showAddDialog = true"
        >
          添加菜单
        </el-button>
      </div>
    </div>
    
    <el-row :gutter="20">
      <!-- 菜单树 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>菜单结构</span>
          </template>
          <el-tree
            :data="menuTree"
            :props="treeProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ data.title }}</span>
                <span class="tree-actions">
                  <el-button 
                    size="small" 
                    type="primary" 
                    @click.stop="editMenu(data)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click.stop="deleteMenu(data)"
                  >
                    删除
                  </el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      
      <!-- 菜单配置 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>菜单配置</span>
          </template>
          <div v-if="selectedMenu" class="menu-config">
            <h3>{{ selectedMenu.title }} - 菜单设置</h3>
            <el-form :model="menuForm" label-width="100px">
              <el-form-item label="菜单名称">
                <el-input v-model="menuForm.title" />
              </el-form-item>
              <el-form-item label="菜单路径">
                <el-input v-model="menuForm.path" />
              </el-form-item>
              <el-form-item label="菜单图标">
                <el-input v-model="menuForm.icon" placeholder="图标名称" />
              </el-form-item>
              <el-form-item label="排序">
                <el-input-number v-model="menuForm.sort" :min="0" />
              </el-form-item>
              <el-form-item label="状态">
                <el-radio-group v-model="menuForm.status">
                  <el-radio label="active">启用</el-radio>
                  <el-radio label="inactive">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="权限标识">
                <el-input v-model="menuForm.permission" placeholder="权限标识" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="saveMenu" :loading="saving">
                  保存菜单
                </el-button>
                <el-button @click="resetMenu">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div v-else class="no-selection">
            <el-empty description="请选择一个菜单进行配置" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 添加/编辑菜单对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingMenu ? '编辑菜单' : '添加菜单'"
      width="500px"
    >
      <el-form :model="addMenuForm" :rules="menuRules" ref="addMenuFormRef" label-width="100px">
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="addMenuForm.title" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path">
          <el-input v-model="addMenuForm.path" />
        </el-form-item>
        <el-form-item label="父级菜单">
          <el-select v-model="addMenuForm.parentId" placeholder="选择父级菜单" clearable>
            <el-option label="顶级菜单" :value="'0'" />
            <el-option 
              v-for="menu in menuOptions" 
              :key="menu.id" 
              :label="menu.title" 
              :value="menu.resourceCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单图标">
          <el-input v-model="addMenuForm.icon" placeholder="图标名称" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="addMenuForm.sort" :min="0" />
        </el-form-item>
        <el-form-item label="权限标识">
          <el-input v-model="addMenuForm.permission" placeholder="权限标识" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveAddMenu" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { systemApi } from '@/api/admin'

export default {
  name: 'AdminMenus',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const showAddDialog = ref(false)
    const editingMenu = ref(null)
    const selectedMenu = ref(null)
    
    // 菜单表单
    const menuForm = reactive({
      title: '',
      path: '',
      icon: '',
      sort: 0,
      status: 'active',
      permission: ''
    })
    
    // 添加菜单表单
    const addMenuForm = reactive({
      title: '',
      path: '',
      parentId: '0',
      icon: '',
      sort: 0,
      permission: ''
    })
    
    // 表单验证规则
    const menuRules = {
      title: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' }
      ],
      path: [
        { required: true, message: '请输入菜单路径', trigger: 'blur' }
      ]
    }
    
    // 树形配置
    const treeProps = {
      children: 'children',
      label: 'title'
    }
    
    // 菜单数据列表
    const menusList = ref([])
    const menuTree = ref([])
    const menuOptions = ref([])

    // 将后端资源列表转为树结构
    const buildMenuTree = (resources) => {
      if (!resources || resources.length === 0) return []
      
      // 标准化字段
      const items = resources.map(r => ({
        id: r.id,
        title: r.resourceName,
        path: r.resourceUrl,
        icon: r.resourceIcon,
        sort: Number(r.resourceSort || 0),
        status: r.resourceStatus === '1' ? 'active' : 'inactive',
        permission: r.resourceCode,
        parentCode: r.parentResourceCode || '0',
        resourceCode: r.resourceCode,
        raw: r
      }))

      // 通过parentResourceCode构建树
      const codeToNode = {}
      const roots = []
      
      // 创建节点映射
      items.forEach(item => {
        codeToNode[item.resourceCode] = { ...item, children: [] }
      })
      
      // 构建树结构
      items.forEach(item => {
        const parentCode = item.parentCode
        if (parentCode && parentCode !== '0' && codeToNode[parentCode]) {
          codeToNode[parentCode].children.push(codeToNode[item.resourceCode])
        } else {
          roots.push(codeToNode[item.resourceCode])
        }
      })
      
      // 按sort排序
      const sortTree = (nodes) => {
        nodes.sort((a,b) => a.sort - b.sort)
        nodes.forEach(n => n.children && n.children.length && sortTree(n.children))
      }
      sortTree(roots)
      return roots
    }

    // 权限检查
    const hasPermission = (permission) => {
      const userInfo = JSON.parse(localStorage.getItem('adminUser') || '{}')
      if (userInfo.permissions?.includes('all')) return true
      return userInfo.permissions?.includes(permission) || false
    }
    
    // 加载菜单数据
    const loadMenus = async () => {
      loading.value = true
      try {
        const response = await systemApi.getMenuList()
        if (response.code === '200') {
          const list = response.data || []
          menusList.value = list
          menuTree.value = buildMenuTree(list)
          // 扁平化作为下拉选项
          const flatten = []
          const dfs = (nodes) => nodes.forEach(n => { flatten.push(n); n.children && dfs(n.children) })
          dfs(menuTree.value)
          menuOptions.value = flatten
          
          // 默认选择第一个菜单
          if (menuTree.value.length > 0) {
            selectMenu(menuTree.value[0])
          }
        }
      } catch (error) {
        console.error('加载菜单数据失败:', error)
        ElMessage.error('加载菜单数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 选择菜单
    const selectMenu = (menu) => {
      selectedMenu.value = menu
      Object.assign(menuForm, {
        title: menu.title,
        path: menu.path,
        icon: menu.icon,
        sort: menu.sort,
        status: menu.status,
        permission: menu.permission
      })
    }
    
    // 编辑菜单
    const editMenu = (menu) => {
      editingMenu.value = menu
      Object.assign(addMenuForm, {
        title: menu.title,
        path: menu.path,
        parentId: menu.parentCode || '0',
        icon: menu.icon,
        sort: menu.sort,
        permission: menu.permission
      })
      showAddDialog.value = true
    }
    
    // 删除菜单
    const deleteMenu = async (menu) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除菜单 "${menu.title}" 吗？此操作不可恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await systemApi.deleteMenu(menu.id)
        if (response.code === '200') {
          ElMessage.success('删除成功')
          loadMenus()
        } else {
          ElMessage.error(response.msg || '删除失败')
        }
      } catch {
        // 用户取消
      }
    }
    
    // 保存菜单
    const saveMenu = async () => {
      if (!selectedMenu.value) {
        ElMessage.warning('请先选择一个菜单')
        return
      }
      
      saving.value = true
      
      try {
        const response = await systemApi.updateMenu({
          id: selectedMenu.value.id,
          resourceName: menuForm.title,
          resourceUrl: menuForm.path,
          resourceIcon: menuForm.icon,
          resourceSort: String(menuForm.sort ?? 0),
          resourceStatus: menuForm.status === 'active' ? '1' : '0',
          resourceCode: menuForm.permission
        })
        
        if (response.code === '200') {
          ElMessage.success('菜单保存成功')
          loadMenus()
        } else {
          ElMessage.error(response.msg || '保存失败')
        }
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }
    
    // 重置菜单
    const resetMenu = () => {
      if (selectedMenu.value) {
        Object.assign(menuForm, {
          title: selectedMenu.value.title,
          path: selectedMenu.value.path,
          icon: selectedMenu.value.icon,
          sort: selectedMenu.value.sort,
          status: selectedMenu.value.status,
          permission: selectedMenu.value.permission
        })
      }
    }
    
    // 保存添加菜单
    const saveAddMenu = async () => {
      saving.value = true
      
      try {
        let response
        if (editingMenu.value) {
          // 编辑菜单
          response = await systemApi.updateMenu({
            id: editingMenu.value.id,
            resourceName: addMenuForm.title,
            resourceUrl: addMenuForm.path,
            parentResourceCode: addMenuForm.parentId === '0' ? null : addMenuForm.parentId,
            resourceIcon: addMenuForm.icon,
            resourceSort: String(addMenuForm.sort ?? 0),
            resourceCode: addMenuForm.permission
          })
        } else {
          // 添加菜单
          response = await systemApi.addMenu({
            resourceName: addMenuForm.title,
            resourceUrl: addMenuForm.path,
            parentResourceCode: addMenuForm.parentId === '0' ? null : addMenuForm.parentId,
            resourceIcon: addMenuForm.icon,
            resourceSort: String(addMenuForm.sort ?? 0),
            resourceCode: addMenuForm.permission
          })
        }
        
        if (response.code === '200') {
          ElMessage.success(editingMenu.value ? '菜单更新成功' : '菜单添加成功')
          showAddDialog.value = false
          editingMenu.value = null
          loadMenus()
        } else {
          ElMessage.error(response.msg || '保存失败')
        }
        
        showAddDialog.value = false
        editingMenu.value = null
        Object.assign(addMenuForm, {
          title: '',
          path: '',
          parentId: '0',
          icon: '',
          sort: 0,
          permission: ''
        })
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        saving.value = false
      }
    }
    
    onMounted(async () => {
      await loadMenus()
    })
    
    return {
      loading,
      saving,
      showAddDialog,
      editingMenu,
      selectedMenu,
      menuForm,
      addMenuForm,
      menuRules,
      treeProps,
      menuTree,
      menuOptions,
      hasPermission,
      selectMenu,
      editMenu,
      deleteMenu,
      saveMenu,
      resetMenu,
      saveAddMenu
    }
  }
}
</script>

<style scoped>
.admin-menus {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.tree-actions {
  display: flex;
  gap: 5px;
}

.menu-config h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
}

.no-selection {
  text-align: center;
  padding: 40px 0;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .custom-tree-node {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .tree-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 